import { AddAdmainHandler, DeleteAdmainHandler, ListAdmainHandler, UpdateAdmainHandler } from '@/api/login';
import menus, { MyMenuItem } from '@/router/memus';
import { Button, Drawer, Input, Popconfirm, Select, Space, Table, Tree, message } from 'antd';
import { ColumnsType } from 'antd/es/table';
// import dayjs from 'dayjs';
import { useEffect, useState, type FC } from 'react';

interface AccountAdminProps { }
interface IArrchildData {
    title: string;
    key: string
}
interface IArrData {
    title: string;
    key: string
    children?: IArrchildData[]
    disabled?: boolean
}
interface DataType {
    adminid: string;
    adminname: string;
    role: number;
    checkedKeys: string[]
}

const AccountAdmin: FC<AccountAdminProps> = () => {
    // 表单的逻辑
    const [current, setCurrent] = useState(1)
    const [btnName, setBtnName] = useState('添加')
    const [adminname, setAdminname] = useState('');
    const [password, setPassword] = useState('');
    const [role, setRole] = useState(1);
    const [checkedKeys, setCheckedKeys] = useState<React.Key[]>(['/', '/set']);
    const [data, setData] = useState([])
    const getTableData = () => {
        ListAdmainHandler().then((res) => {
            setData(res.data.data)
        })
    }
    //  增加管理员方法
    const add = () => {
        if (btnName === '添加') {
            const params = {
                adminname,
                password,
                role,
                checkedKeys
            }
            AddAdmainHandler(params).then((res) => {
                console.log(res.data);
                setAdminname('')
                setPassword('')
                setRole(1)
                setCheckedKeys(['/', '/set'])
                if (res.data.code === '200') {
                    messageApi.open({
                        type: 'success',
                        content: '添加管理员成功',
                    });
                } else if (res.data.code === '10004') {
                    messageApi.open({
                        type: 'warning',
                        content: res.data.message,
                    });
                }
                onClose()
                getTableData()
            })
        } else {
            const params = {
                adminname,
                role,
                checkedKeys
            }
            console.log(params);
            UpdateAdmainHandler(params).then((res) => {
                console.log(res);
                if (res.data.code === '200') {
                    messageApi.open({
                        type: 'success',
                        content: '更新管理员成功',
                    });
                }
                onClose()
                getTableData()
            });
        }

    }
    const columns: ColumnsType<DataType> = [
        {
            title: '序号',
            render: (text: DataType, record: DataType, index: number) => {
                return (
                    <span>{(current - 1) * 10 + (index + 1)}</span>
                )
            }
        },
        {
            title: '用户名',
            dataIndex: 'adminname'
        },
        {
            title: '权限',
            dataIndex: 'role',
            render: (text) => {
                return (
                    <span>{text === 2 ? '超级管理员' : '管理员'}</span>
                )
            }
        },
        {
            title: '操作',
            render: (text: DataType, record: DataType, index: number) => {
                return (
                    <Space>
                        <Button type='dashed' onClick={() => {
                            console.log(text);
                            setBtnName('更新')
                            setOpen(true);
                            setAdminname(text.adminname)
                            setRole(text.role)
                            setCheckedKeys(text.checkedKeys)

                        }}>编辑</Button>
                        <Popconfirm
                            title="删除数据"
                            description="你确定要删除这条数据吗?"
                            onConfirm={() => {
                                console.log(text, index);
                                DeleteAdmainHandler({ adminid: text.adminid }).then(res => {
                                    console.log(res);
                                    if (res.data.code === '200') {
                                        messageApi.open({
                                            type: 'success',
                                            content: '删除管理员成功',
                                        });
                                    }
                                    getTableData()
                                })
                            }}
                            okText="确定"
                            cancelText="取消"
                        >
                            <Button danger>删除</Button>
                        </Popconfirm>
                    </Space>
                )
            }
        }
    ]

    useEffect(() => {
        getTableData()
    }, [])
    // 抽屉逻辑
    const [open, setOpen] = useState(false);
    const showDrawer = () => {
        setAdminname('')
        setPassword('')
        setRole(1)
        setCheckedKeys(['/', '/set'])
        setOpen(true);
        setBtnName('添加')
    };
    const onClose = () => {
        setOpen(false);
    };
    // 修改管理员账号
    const changeAdminname = ({ target }: { target: HTMLInputElement }) => {
        console.log(target.value);
        setAdminname(target.value)
    }
    // 修改管理员密码
    const changePassword = ({ target }: { target: HTMLInputElement }) => {
        console.log(target.value);
        setPassword(target.value)
    }
    // 修改管理员账号
    const changeRole = (value: number) => {
        console.log(value);
        setRole(value)
    }
    // 消息提示的组件
    const [messageApi, contextHolder] = message.useMessage();
    // 树状结构逻辑
    // 整合路由的数据变为tree要的数据
    const gettreeData = (menus: MyMenuItem[]) => {
        const arr: IArrData[] = []
        let obj: IArrData = {
            key: '',
            title: ''
        }
        menus.forEach(item => {
            if (item.children) {
                const childList = gettreeData(item.children)
                if (item.key === '/map') {
                    obj = {
                        title: item.label,
                        key: item.key as string,
                        children: childList!,
                        disabled: true
                    }
                } else {
                    obj = {
                        title: item.label,
                        key: item.key as string,
                        children: childList!,
                    }
                }
            } else {
                obj = {
                    title: item.label,
                    key: item.key as string,
                }
            }
            arr.push(obj)
        })
        return arr
    }
    const treeData: IArrData[] = gettreeData(menus)
    const onCheck = (checkedKeysValue: any) => {
        setCheckedKeys(checkedKeysValue);
    };
    const height = document.body.clientHeight
    const onChange = (page: any, pageSize: any) => {
        setCurrent(page)
    }
    return (
        <Space direction="vertical" style={{ width: '100%' }}>
            {contextHolder}
            <Button type="primary" onClick={() => showDrawer()}>添加管理员</Button>
            <Table
                columns={columns}
                dataSource={data}
                scroll={{ y: height - 330 }}
                rowKey='adminid'
                pagination={
                    {
                        total: data.length,
                        showTotal: (total) => `共 ${total} 条数据`,
                        showQuickJumper: true,
                        showSizeChanger: true,
                        onChange,
                        pageSizeOptions: [5, 10, 20, 50]
                    }
                }
            />;
            <Drawer title={btnName + '管理员'} placement="right" onClose={onClose} open={open}>
                <Space direction='vertical' style={{ width: '100%' }}>
                    <Input placeholder='管理员账号' value={adminname} onChange={changeAdminname} disabled={btnName === '添加' ? false : true} />
                    <Input placeholder='管理员密码' value={password} onChange={changePassword} disabled={btnName === '添加' ? false : true} />
                    <Select
                        style={{ width: '100%' }}
                        onChange={changeRole}
                        value={role}
                        options={[
                            { value: 1, label: '管理员' },
                            { value: 2, label: '超级管理员' },
                        ]}></Select>
                </Space>
                <Space direction='vertical' style={{ width: '100%' }}>
                    <Tree
                        checkable
                        onCheck={onCheck}
                        checkedKeys={checkedKeys}
                        treeData={treeData}
                    />
                </Space>
                <Button type="primary" onClick={() => add()}>{btnName}</Button>
            </Drawer>
        </Space>
    );
}

export default AccountAdmin;

